// ==UserScript==
// @name         一键投币
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.bilibili.com/video/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=firefoxchina.cn
// @grant        none
// ==/UserScript==
const bubbleClick = new MouseEvent('click', {bubbles: true})
let htmlText = `
<div id="bili-coin-script" draggable="true">
  <button id="do-coin">一键投币</button>
</div>
<style>
  #bili-coin-script{
    width: 200px;
    height: 100px;
    border-radius: 10px;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-content: space-around;
    position: fixed;
    right: 5px;
    top: 100px;
    z-index: 500;
    background-color: rgb(198, 194, 194);
  }
  #bili-coin-script > input{
    border: 1px gray;
    font-size: 13px;
    color: black;
  }
  #bili-coin-script > button{
    font-size: 13px;
    color: red;
    margin: 0 20px;
  }
</style>
`
// 立即执行函数前面必须加分号
// 脚本执行入口
;(function(){
  window.onload = () => {
    console.log('脚本运行')
    doCoinWrapper(10)
  }
})();

// 初始化脚本dom
function initDom(){
  let div = document.createElement('div')
  div.innerHTML = htmlText
  document.querySelector('body').append(div)
}

function handleEvent(){
  const btn = document.querySelector('#do-coin')
  btn.addEventListener('click', () => {
    console.log(getVideoList())
  })
}

function getVideoList(){
  let aList = document.querySelectorAll('a')
  let videoList = []
  aList.forEach(a => {
    if(/\/video\//.test(a.href)){
      let url = 'https://www.bilibili.com' + a.href.substring(a.href.indexOf('/video/'))
      videoList.push({
        url,
        done: false,
        num: 1,
      })
    }
  })
  return videoList
}

async function doCoin(){
  let coinHistoryStr = localStorage.getItem('coinHistory')
  let coinHistory = {date: timeFormat(new Date()), full: false}
  if(coinHistoryStr){
    coinHistory = JSON.parse(coinHistoryStr)
  }

  let nowDate = timeFormat(new Date())
  if(coinHistory.date == nowDate && coinHistory.full){
    return 
  }
  if(coinHistory.date != nowDate){
    coinHistory.date = nowDate
    coinHistory.full = false
  }

  localStorage.setItem('coinHistory', JSON.stringify(coinHistory))

  document.querySelector('.video-coin-icon').dispatchEvent(new MouseEvent('click', {bubbles:true}))
  await sleep(500)

  let tipsText = document.querySelector('.tips').innerHTML
  if(/经验值\+[0-9]{2,2}/.test(tipsText) == false){
    let closeIcon = document.querySelector('i[class="icon close"]')
    closeIcon.dispatchEvent(new MouseEvent('click', {bubbles:true}))
    coinHistory.full = true
    localStorage.setItem('coinHistory', JSON.stringify(coinHistory))
    return 1
  }
  
  document.querySelector('.left-con').dispatchEvent(new MouseEvent('click', {bubbles:true}))
  await sleep(500)
  document.querySelector('.bi-btn').dispatchEvent(new MouseEvent('click', {bubbles:true}))
}

// 执行doCoin，如果出错的话等五秒后重新执行
function doCoinWrapper(counter){
  if(counter > 0){
    console.log('尝试: counter = ', counter)
    doCoin().catch(() => {
      setTimeout(() => {
        doCoinWrapper(counter - 1)
      }, 5000)
    })
  }
}

function sleep(timeout){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1)
    }, timeout)
  })
}

// 格式化时间
function timeFormat(date){
  let yyyy = date.getFullYear().toString()
  let mm = (date.getMonth() + 1).toString().padStart(2, '0')
  let dd = date.getDay().toString().padStart(2, '0')
  let hh = date.getHours().toString().padStart(2, '0')
  let ss = date.getMinutes().toString().padStart(2, '0')
  return yyyy + mm + dd
}